
package fileby.ctrl.transferhandlers.impl;

import fileby.model.IFileManager;
import fileby.model.ISelectionManager;
import fileby.model.ISourceHandler;
import fileby.util.TransferableFileUtil;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.TransferHandler;

/**
 *
 * @author Oscar
 */
class ItemPanelTransferHandler extends TransferHandler {

    private IFileManager fileManager;
    private ISourceHandler sourceHandler;
    private ISelectionManager selectionManager;


    public ItemPanelTransferHandler(IFileManager fileManager,
            ISourceHandler sourceHandler, ISelectionManager selectionManager) {
        super();
        this.fileManager = fileManager;
        this.sourceHandler = sourceHandler;
        this.selectionManager = selectionManager;
    }

     /*
     * This method indicates whether a component would accept an import
     * of the given set of data flavors prior to actually attempting to
     * import it. In this case we only support javaFileListFlavor.
     */
    @Override
    public boolean canImport(TransferHandler.TransferSupport support) {
        if(!new File(support.getComponent().getName()).isDirectory())
            return false;
        return support.isDataFlavorSupported(DataFlavor.javaFileListFlavor);
    }

    /*
     *  Causes a transfer with files to a component from the DnD action.
     */
    @Override
    public boolean importData(TransferHandler.TransferSupport support) {
        support.getComponent().getName();
        Transferable t = support.getTransferable();
        try {
            List<File> fileList = (List<File>) t.getTransferData(DataFlavor.javaFileListFlavor);
            fileManager.addFilesInDirectory(fileList, support.getComponent().getName(), support.getDropAction());
        } catch (UnsupportedFlavorException e) {
            return false;
        } catch (IOException e) {
            return false;
        }
        return true;
    }

   @Override
   protected void exportDone(JComponent source, Transferable data, int action) {
       super.exportDone(source, data, action);
       sourceHandler.updateSource();
   }
   
    @Override
    public Transferable createTransferable(JComponent c) {
       return new TransferableFileUtil(selectionManager.getSelectedFiles()); //returns a FileSelection, list of files that can be transferd.
    }

    @Override
    public int getSourceActions (JComponent c) {
        return COPY_OR_MOVE;
    }

}
